package com.goods.crawler.facade;

import com.goods.crawler.entity.Proxyip;
import com.goods.crawler.service.IpTransferService;
import com.goods.crawler.utils.WebDriverFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

/**
* <pre>类名: IpTransferFacade</pre>
* <pre>描述: 爬取动态ip facade</pre>
* <pre>版权: 浙江理工大学信息学院</pre>
* <pre>日期: 2019/2/17 16:47</pre>
* <pre>作者: chenwb</pre>
*/
@Service
public class IpTransferFacade {
	private static Logger logger = LoggerFactory.getLogger(IpTransferFacade.class);

	@Autowired
	IpTransferService ipTransferService;

	public static String proxyIpUrl = "https://www.xicidaili.com/wn/";

	@Scheduled(cron = "0 0 0/3 * * ?")
	public void crawlerDynamicIp(){
		WebDriver driver = WebDriverFactory.getInstance();
		logger.info("---------------开始爬取代理ip------------------");
		driver.get(proxyIpUrl);
		List<WebElement> elementList = driver.findElement(By.id("ip_list")).findElements(By.tagName("tr")); //不包含第一条
		List<Proxyip> proxyipList = new ArrayList<Proxyip>();
		for (int i = 1; i < elementList.size(); i++) {
			List<WebElement> webElements =  elementList.get(i).findElements(By.tagName("td"));
			String ipAddress = webElements.get(1).getText();
			String port = webElements.get(2).getText();
			//String serverAddress = webElements.get(3).findElement(By.tagName("a")).getText();
			String checkTime = webElements.get(9).getText();
			Date date = new Date(System.currentTimeMillis());
			Proxyip proxyip = new Proxyip(ipAddress,port,"serverAddress",checkTime,date);
			proxyipList.add(proxyip);
		}
		ipTransferService.saveAllDynamicIp(proxyipList);
		logger.info("---------------爬取代理ip结束------------------");
		driver.quit();
	}

	/**
	 * @Description: checkProxyIps
	 * @author chenwb
	 * @date 2019/2/17 20:07
	 * @param 输入参数
	 * @return 输出参数
	 */
	@Scheduled(cron = "0 0/1 0 * * ?")
	public void checkProxyIps(){

	}
}
